package com.thinkmore.mybatisplus.intercuptor;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

/**
 * 多租户和特定sql过滤器
 * 1、Intercepts注解不可少，springmvc必须有
 */
@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class}
)})
public class MyPageInterceptor extends MybatisPlusInterceptor {
    public static ThreadLocal<String> myTableName = new ThreadLocal<>();

    public MyPageInterceptor() {
        this.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        /*DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
        dynamicTableNameParser.setTableNameHandlerMap(new HashMap<String, ITableNameHandler>(2) {{
            put("auto_fill", (metaObject, sql, tableName) -> {
                // metaObject 可以获取传入参数，这里实现你自己的动态规则
                if (sql.startsWith("select")) {
                    String year = "_2018";
                    int random = new Random().nextInt(10);
                    if (random % 2 == 1) {
                        year = "_2019";
                    }
                    return tableName + year;
                }
                return tableName;
            });
        }});
        this.setSqlParserList(Collections.singletonList(dynamicTableNameParser));*/
    }
}
